/*
Copyright 2023 The Godel Scheduler Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package queue

import (
	"fmt"

	"github.com/kubewharf/godel-scheduler-api/pkg/client/listers/scheduling/v1alpha1"
	"go.opentelemetry.io/otel/trace"
	v1 "k8s.io/api/core/v1"
	ktypes "k8s.io/apimachinery/pkg/types"
	schedulingv1 "k8s.io/client-go/listers/scheduling/v1"
	k8smetrics "k8s.io/component-base/metrics"

	pkgmetrics "github.com/kubewharf/godel-scheduler/pkg/common/metrics"
	framework "github.com/kubewharf/godel-scheduler/pkg/framework/api"
	"github.com/kubewharf/godel-scheduler/pkg/framework/utils"
	"github.com/kubewharf/godel-scheduler/pkg/scheduler/metrics"
	"github.com/kubewharf/godel-scheduler/pkg/util"
	"github.com/kubewharf/godel-scheduler/pkg/util/heap"
)

// waitingPods holds the pods in the same podgroup (that we can't create ScheduleUnit for now).
type waitingPods struct {
	unitKey string
	pods    map[ktypes.UID]*framework.QueuedPodInfo
	// used by metrics and tracing
	// generated by call GetUnitProperty()
	unitProperty framework.UnitProperty
}

var (
	_ framework.StoredUnit     = &waitingPods{}
	_ framework.ObservableUnit = &waitingPods{}
)

func (w *waitingPods) GetUnitProperty() framework.UnitProperty {
	if w.unitProperty != nil {
		return w.unitProperty
	}
	p := newWaitingPodsProperty(w)
	if p == nil {
		return nil
	}
	w.unitProperty = p
	return w.unitProperty
}

func (w *waitingPods) GetKey() string {
	return w.unitKey
}

// GetPods implement the StoredUnit interface.
func (w *waitingPods) GetPods() []*framework.QueuedPodInfo {
	var result []*framework.QueuedPodInfo
	for _, pInfo := range w.pods {
		result = append(result, pInfo)
	}
	return result
}

// NumPods implement the StoredUnit interface.
func (w *waitingPods) NumPods() int {
	return len(w.pods)
}

func (w *waitingPods) transferToPodGroupUnit(
	pcLister schedulingv1.PriorityClassLister,
	pgLister v1alpha1.PodGroupLister,
	clock util.Clock,
) *framework.QueuedUnitInfo {
	if w == nil {
		return nil
	}
	var randomPodInfo *framework.QueuedPodInfo
	for uid := range w.pods {
		randomPodInfo = w.pods[uid]
		break
	}
	if randomPodInfo == nil {
		return nil
	}
	scheduleUnit, err := utils.CreateScheduleUnit(pcLister, pgLister, randomPodInfo)
	if err != nil {
		return nil
	}
	for i := range w.pods {
		scheduleUnit.AddPod(w.pods[i])
	}
	return framework.NewQueuedUnitInfo(scheduleUnit.GetKey(), scheduleUnit, clock)
}

func waitingPodsKeyFunc(obj interface{}) (string, error) {
	if obj == nil {
		return "", fmt.Errorf("waitingPodsKeyFunc: obj is nil")
	}
	o := obj.(*waitingPods)
	return o.unitKey, nil
}

// waitingPods holds all pods in different units.
type waitingPodsList struct {
	SubQueue
	clock util.Clock
}

var _ SubQueue = &waitingPodsList{}

func newWaitingPodsList(qos, subCluster, ownerName string, clock util.Clock) *waitingPodsList {
	return &waitingPodsList{
		SubQueue: heap.NewWithRecorder("waitingPodsList", waitingPodsKeyFunc, alwaysFalse, metrics.NewPendingUnitsRecorder("waitingPodsList")),
		clock:    clock,
	}
}

func (w *waitingPodsList) removeExistedOrCreateWaitingPods(pod *v1.Pod) *waitingPods {
	unitKey := utils.GetUnitIdentifier(pod)
	if obj, exist, _ := w.SubQueue.GetByKey(unitKey); exist {
		// For the accuracy of metrics, delete the waitingPods before modifying it.
		w.SubQueue.DeleteByKey(unitKey)
		return obj.(*waitingPods)
	}
	return &waitingPods{
		unitKey: unitKey,
		pods:    make(map[ktypes.UID]*framework.QueuedPodInfo),
	}
}

func (w *waitingPodsList) Add(obj interface{}) error {
	pod := obj.(*v1.Pod)
	podInfo := newQueuedPodInfo(pod, w.clock)
	wp := w.removeExistedOrCreateWaitingPods(pod)
	wp.pods[pod.UID] = podInfo
	return w.SubQueue.Add(wp)
}

func (w *waitingPodsList) Update(oldObj, newObj interface{}) error {
	oldPod, newPod := oldObj.(*v1.Pod), newObj.(*v1.Pod)
	// We assume that the oldPod and the newPod belong to a same unit.
	wp := w.removeExistedOrCreateWaitingPods(newPod)
	if oldPodInfo, ok := wp.pods[oldPod.UID]; ok {
		delete(wp.pods, oldPodInfo.Pod.UID)
		wp.pods[newPod.UID] = updatePodInfo(oldPodInfo, newPod)
	} else {
		wp.pods[newPod.UID] = newQueuedPodInfo(newPod, w.clock)
	}
	return w.SubQueue.Add(wp)
}

func (w *waitingPodsList) Delete(obj interface{}) error {
	pod := obj.(*v1.Pod)
	wp := w.removeExistedOrCreateWaitingPods(pod)
	delete(wp.pods, pod.UID)
	if len(wp.pods) > 0 {
		return w.SubQueue.Add(wp)
	}
	return nil
}

func newWaitingPodsProperty(w *waitingPods) framework.UnitProperty {
	var podProperty *framework.PodProperty
	for _, podInfo := range w.pods {
		podProperty = framework.ExtractPodProperty(podInfo.Pod)
		if podProperty != nil {
			break
		}
	}

	if podProperty == nil {
		return nil
	}

	return &waitingPodsProperty{
		PodProperty: podProperty,
		UnitType:    string(framework.PodGroupUnitType),
	}
}

type waitingPodsProperty struct {
	// TODO: figure out whether we can embed PodProperty into ScheduleUnitProperty
	*framework.PodProperty
	UnitType string
}

func (wpp *waitingPodsProperty) GetPodProperty() *framework.PodProperty {
	return wpp.PodProperty
}

func (wpp *waitingPodsProperty) ConvertToMetricsLabels() k8smetrics.Labels {
	labels := wpp.PodProperty.ConvertToMetricsLabels()
	labels[pkgmetrics.UnitTypeLabel] = wpp.UnitType

	return labels
}

func (wpp *waitingPodsProperty) ConvertToTracingTags() trace.SpanOption {
	return trace.WithAttributes()
}
